package ConveyorBelt.State;

import java.util.Hashtable;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;


import ConveyorBelt.Level.CurrentLevel;
import ConveyorBelt.Level.LevelLoader;
import ConveyorBelt.Util.FontUtil;
import ConveyorBelt.Util.ImageUtil;


public class Game extends BasicGameState {
	public static final int stateID = 1;
	public static Integer levelNumber = 1;
	public CurrentLevel currentLevel = null;
	public  LevelLoader loader = null;
	public Hashtable<String, String> levelChain;
    public StateBasedGame sbg;
    
	@Override
	public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
		this.sbg = sbg;
		ImageUtil.loadAllImage();
		FontUtil.loadGameFont();
		try {
			loader = new LevelLoader("resources/map/level.properties");
			levelChain = loader.getLevelChain();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		if(levelNumber > levelChain.size()) sbg.enterState(EndOfGame.stateID, new FadeOutTransition(Color.black), new FadeInTransition(Color.black));
		if(levelNumber <= levelChain.size()) {
			currentLevel = new CurrentLevel(levelChain.get(levelNumber.toString()), levelNumber);
		}
	}	

	@Override
	public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
		ImageUtil.background.draw(0, 0);
		currentLevel.render(this, g);
	}

	@Override
	public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
		currentLevel.update(gc, delta);
		if(levelNumber < levelChain.size()) {
			if(currentLevel.isLevelWon()) {	
				levelNumber++;
				sbg.enterState(LevelWin.stateID, new FadeOutTransition(Color.black), new FadeInTransition(Color.black));
				return;
			}	
		}
		else if(levelNumber == levelChain.size()) {
			if(currentLevel.isLevelWon()) {	
				sbg.enterState(EndOfGame.stateID, new FadeOutTransition(Color.black), new FadeInTransition(Color.black));
				return;
			}	
		}
		if(currentLevel.isLevelLose()) {
			sbg.enterState(LevelLose.stateID, new FadeOutTransition(Color.black), new FadeInTransition(Color.black));
			return;
		}
	}
	@Override
	public void keyPressed(int key, char c) {
		if(key == Input.KEY_ESCAPE)  sbg.enterState(Pause.stateID, new FadeOutTransition(Color.black), new FadeInTransition(Color.black));
	}
	@Override
	public int getID() {
		return stateID;  
	}
}
